<?php
namespace app\admin\model;
use think\Model;
/**
 * 商品模型
 */
class GoodsModel extends Model
{	
	 // 设置当前模型对应的完整数据表名称
    protected $table = 'tp_goods';
    protected $field = true;//数据表中无此字段忽略
	protected static function init(){
		GoodsModel::beforeInsert(function ($goods) {
			if($_FILES['og_thumb']['tmp_name']){
		          $thumbName= $goods->upload('og_thumb');
		          $ogThumb=date('Ymd').DS.$thumbName;
		          $smThumb=date('Ymd').DS.'sm_'.$thumbName;
		          $midThumb=date('Ymd').DS.'mid_'.$thumbName;
		          $bigThumb=date('Ymd').DS.'big_'.$thumbName;
			      $image = \think\Image::open(IMG_UPLOADS.$ogThumb);
				$image->thumb(500, 500)->save(IMG_UPLOADS.$bigThumb);
				$image->thumb(300, 300)->save(IMG_UPLOADS.$midThumb);
				$image->thumb(150, 150)->save(IMG_UPLOADS.$smThumb);
				$goods->og_thumb=$ogThumb;
	            $goods->big_thumb=$bigThumb;
	            $goods->mid_thumb=$midThumb;
	            $goods->sm_thumb=$smThumb;
	        }
	            $goods->goods_code=time().rand(111111,999999);//商品编号
        });
        GoodsModel::beforeUpdate(function ($goods) {
            // 商品id
            $goodsId=$goods->id;
           
            if($_FILES['og_thumb']['tmp_name']){
                // 如果原来有就删除
                @unlink(IMG_UPLOADS.$goods->og_thumb);
                @unlink(IMG_UPLOADS.$goods->big_thumb);
                @unlink(IMG_UPLOADS.$goods->mid_thumb);
                @unlink(IMG_UPLOADS.$goods->sm_thumb);
                  $thumbName= $goods->upload('og_thumb');
                  $ogThumb=date('Ymd').DS.$thumbName;
                  $smThumb=date('Ymd').DS.'sm_'.$thumbName;
                  $midThumb=date('Ymd').DS.'mid_'.$thumbName;
                  $bigThumb=date('Ymd').DS.'big_'.$thumbName;
                  $image = \think\Image::open(IMG_UPLOADS.$ogThumb);
                $image->thumb(500, 500)->save(IMG_UPLOADS.$bigThumb);
                $image->thumb(300, 300)->save(IMG_UPLOADS.$midThumb);
                $image->thumb(150, 150)->save(IMG_UPLOADS.$smThumb);
                $goods->og_thumb=$ogThumb;
                $goods->big_thumb=$bigThumb;
                $goods->mid_thumb=$midThumb;
                $goods->sm_thumb=$smThumb;
            }
        });
         GoodsModel::afterUpdate(function($goods){

            // 商品id
            $goodsId=$goods->id;
            //接受表单数据
            $goodsData=input('post.');
            // dump($goodsData);die;
            db('item')->where(array('value_type'=>1,'value_id'=>$goodsId))->delete();
            // 处理商品推荐位
            if (isset($goodsData['recpos'])) {
               foreach ($goodsData['recpos'] as $k => $v) {
                  db('item')->insert(['recpos_id'=>$v,'value_type'=>1,'value_id'=>$goodsId]);
               }
            }
             // 处理会员价格
            $mpriceArr=$goods->mp;
            // 删除原有会员价格
            db('member_price')->where('goods_id',$goodsId)->delete();
            //批量插入会员价格
            if ($mpriceArr) {
                foreach ($mpriceArr as $k => $v) {
                    if (trim($v)=='') {
                        continue;
                    }else{
                        db('member_price')->insert(['mlevel_id'=>$k,'mprice'=>$v,'goods_id'=>$goodsId]);
                    }
                }
            }
             if(isset($goodsData['goods_attr'])){
                $i=0;
                foreach ($goodsData['goods_attr'] as $k => $v) {
                    if(is_array($v)){
                        if(!empty($v)){
                            foreach ($v as $k1 => $v1) {
                                if(!$v1){
                                    $i++;
                                    continue;
                                }
                                db('goods_attr')->insert(['attr_id'=>$k,'attr_value'=>$v1,'attr_price'=>$goodsData['attr_price'][$i],'goods_id'=>$goodsId]);
                                $i++;
                            }
                        }
                    }else{
                        // 处理唯一属性类型
                        db('goods_attr')->insert(['attr_id'=>$k,'attr_value'=>$v,'goods_id'=>$goodsId]);
                    }
                }
            }
            // 修改商品属性
            if(isset($goodsData['old_goods_attr'])){
                $attrPrice=$goodsData['old_attr_price'];
                $idsArr=array_keys($attrPrice);
                $valuesArr=array_values($attrPrice);
                $i=0;
                foreach ($goodsData['old_goods_attr'] as $k => $v) {
                    if(is_array($v)){
                        if(!empty($v)){
                            foreach ($v as $k1 => $v1) {
                                if(!$v1){
                                    $i++;
                                    continue;
                                }
                                db('goods_attr')->where('id','=',$idsArr[$i])->update(['attr_value'=>$v1,'attr_price'=>$valuesArr[$i]]);
                                $i++;
                            }
                        }
                    }else{
                        // 处理唯一属性类型
                        db('goods_attr')->where('id','=',$idsArr[$i])->update(['attr_value'=>$v,'attr_price'=>$valuesArr[$i]]);
                        $i++;
                    }
                }
            }
            // 商品相册处理
            if ($goods->_hasImgs($_FILES['goods_photo']['tmp_name'])) {
                $files=request()->file('goods_photo');
                foreach ($files as $file) {
                     $info = $file->move(ROOT_PATH . 'public' . DS .'static'.DS. 'uploads');
                     if ($info) {
                        $photoName=$info->getFilename();
                        $ogThumb=date('Ymd').DS.$photoName;
                        $smThumb=date('Ymd').DS.'sm_'.$photoName;
                        $midThumb=date('Ymd').DS.'mid_'.$photoName;
                        $bigThumb=date('Ymd').DS.'big_'.$photoName;
                        $image = \think\Image::open(IMG_UPLOADS.$ogThumb);
                        $image->thumb(300, 300)->save(IMG_UPLOADS.$bigThumb);
                        $image->thumb(150, 150)->save(IMG_UPLOADS.$midThumb);
                        $image->thumb(80, 80)->save(IMG_UPLOADS.$smThumb);
                        db('goods_photo')->insert(['goods_id'=>$goodsId,'sm_photo'=>$smThumb,'mid_photo'=>$midThumb,'big_photo'=>$bigThumb,'og_photo'=>$ogThumb]);
                     }
                }
            }
        });
        GoodsModel::afterInsert(function($goods){

        	// 商品id
            $goodsId=$goods->id;
            //接受表单数据
            $goodsData=input('post.');
            // 处理商品推荐位
            if (isset($goodsData['recpos'])) {
               foreach ($goodsData['recpos'] as $k => $v) {
                  db('item')->insert(['recpos_id'=>$v,'value_type'=>1,'value_id'=>$goodsId]);
               }
            }
            // 处理商品属性
            if (isset($goodsData['goods_attr'])) {
            	$i=0;
            	foreach ($goodsData['goods_attr'] as $k => $v) {
            		if (is_array($v)) {
            			if (!empty($v)) {
            				foreach ($v as $k1 => $v1) {
            					if (!$v1) {
            						$i++;
            						continue;
            					}
            					db('goods_attr')->insert(['attr_id'=>$k,'attr_value'=>$v1,'attr_price'=>$goodsData['attr_price'][$i],'goods_id'=>$goodsId]);
            					$i++;
            				}
            			}
            		}else{
            			// 唯一属性
            			db('goods_attr')->insert(['attr_id'=>$k,'attr_value'=>$v,'goods_id'=>$goodsId]);
            		}
            	}
            }
        	
        	// 商品id
            // $goodsId=$goods->id;
        	$mpriceArr=$goods->mp;
        	//批量插入会员价格
        	if ($mpriceArr) {
        		foreach ($mpriceArr as $k => $v) {
        			if (trim($v)=='') {
        				continue;
        			}else{
        				db('member_price')->insert(['mlevel_id'=>$k,'mprice'=>$v,'goods_id'=>$goodsId]);
        			}
        		}
        	}
        	// 商品相册处理
        	if ($goods->_hasImgs($_FILES['goods_photo']['tmp_name'])) {
        		$files=request()->file('goods_photo');
        		foreach ($files as $file) {
        			 $info = $file->move(ROOT_PATH . 'public' . DS .'static'.DS. 'uploads');
        			 if ($info) {
        			 	$photoName=$info->getFilename();
				        $ogThumb=date('Ymd').DS.$photoName;
				        $smThumb=date('Ymd').DS.'sm_'.$photoName;
				        $midThumb=date('Ymd').DS.'mid_'.$photoName;
				        $bigThumb=date('Ymd').DS.'big_'.$photoName;
					    $image = \think\Image::open(IMG_UPLOADS.$ogThumb);
						$image->thumb(300, 300)->save(IMG_UPLOADS.$bigThumb);
						$image->thumb(150, 150)->save(IMG_UPLOADS.$midThumb);
						$image->thumb(80, 80)->save(IMG_UPLOADS.$smThumb);
						db('goods_photo')->insert(['goods_id'=>$goodsId,'sm_photo'=>$smThumb,'mid_photo'=>$midThumb,'big_photo'=>$bigThumb,'og_photo'=>$ogThumb]);
        			 }
        		}
        	}
        });
        GoodsModel::beforeDelete(function($goods){
        	$goodsId=$goods->id;
            // 删除主图及缩略图
            if ($goods->og_thumb) {
                $thumb=[];
                $thumb[]=IMG_UPLOADS.$goods->og_thumb;
                $thumb[]=IMG_UPLOADS.$goods->sm_thumb;
                $thumb[]=IMG_UPLOADS.$goods->mid_thumb;
                $thumb[]=IMG_UPLOADS.$goods->big_thumb;
                foreach ($thumb as $k => $v) {
                   if (file_exists($v)) {
                      @unlink($v);
                   }
                }
            }
           // 删除相关会员价格
           db('member_price')->where('goods_id',$goodsId)->delete();
           // 删除关联商品属性
            db('goods_attr')->where('goods_id',$goodsId)->delete();
            // 删除关联的商品相册
             $goodsPhotoRes=db('goods_photo')->where('goods_id',$goodsId)->select();

             if (!empty($goodsPhotoRes)) {
                 foreach ($goodsPhotoRes as $k => $v) {
                    if ($v['og_photo']) {
                        $photo=[];
                        $photo[]=IMG_UPLOADS.$v['og_photo'];
                        $photo[]=IMG_UPLOADS.$v['sm_photo'];
                        $photo[]=IMG_UPLOADS.$v['mid_photo'];
                        $photo[]=IMG_UPLOADS.$v['big_photo'];
                        // halt($photo);
                        foreach ($photo as $k1 => $v1) {
                           if (file_exists($v1)) {
                              @unlink($v1);
                           }
                        }
                    }
                 }
             }
             db('goods_photo')->where('goods_id',$goodsId)->delete();

        });

        
	}
	// 商品相册是否有图片上传的判断
        private function _hasImgs($tmpArr){
        	foreach ($tmpArr as $k => $v) {
        		if ($v) {
        			return true;
        		}
        	}
        	return false;
        }
	public function upload($imgName){
		$file = request()->file($imgName);
	    if($file){
	        $info = $file->move(ROOT_PATH . 'public' . DS . 'static'. DS . 'uploads');
	        if($info){
	            return $info->getFilename(); 
	        }else{
	            echo $file->getError();
	        }
	    }
	}
	
}